//
//  MapViewController.m
//  DNDzgz
//
//  Created by gimenete on 28/04/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"

#import "DNDzgzAppDelegate.h"

#define secondsInADay 24*60*60

@implementation MapViewController
@synthesize mapView;

- (id)initWithService:(NSString *) service
{
	self = [super init];
	if(nil != self)
	{
		serviceKey = service;
		[serviceKey retain];
	}
	
	return self;
}

- (void)viewDidLoad 
{
	[super viewDidLoad];
	
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta=0.005;
	span.longitudeDelta=0.005;
	
	CLLocationCoordinate2D location = {41.641184, -0.894032};
	region.span=span;
	region.center=location;
	
	[mapView setRegion:region];

	centerButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"locatePin.png"]
																style:UIBarButtonItemStyleBordered 
																target:self 
																action:@selector(moveToUserLocation)];
	centerButton.enabled = NO;
	self.navigationItem.rightBarButtonItem = centerButton;
		
	
	[self loadAnnotations];

	
	[mapView.userLocation addObserver:self forKeyPath:@"location"
							  options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial
							  context:nil];
}

- (BOOL)containsString:(NSString *)aString inOriginalNSSString:(NSString *)originalStr
{
	NSRange range = [[originalStr lowercaseString] rangeOfString:[aString lowercaseString]];
	
	if (range.location != NSNotFound) 
	{
		return YES;
	}
	else 
	{
		return NO;
	}
}

- (void)loadAnnotations
{
	NSString *data = nil;
	
	// check if serviceKey is cached and is not older than 24 h.
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSDate *now = [NSDate date];
	
	NSString *lastUpdateKey = [[NSString alloc] initWithFormat:@"%@-lastUpdate", serviceKey];
	NSNumber *lastUpdate = [defaults objectForKey: lastUpdateKey];
	[lastUpdateKey release];
	
	//lastUpdate && 
	NSLog(@"Interval: %f", [lastUpdate doubleValue] + secondsInADay);
	NSLog(@"Now: %f", [now timeIntervalSince1970]);
	
	/*
	NSString *statePreloadedBus = [(DNDzgzAppDelegate *)[UIApplication sharedApplication].delegate preLodadedBus];
	NSString *statePreloadedBizi = [(DNDzgzAppDelegate *)[UIApplication sharedApplication].delegate preLodadedBizi];
	NSString *statePreloadedWifi = [(DNDzgzAppDelegate *)[UIApplication sharedApplication].delegate preLodadedWifi];
	[(DNDzgzAppDelegate *)[UIApplication sharedApplication].delegate setService:serviceKey];
	
	
	if((statePreloadedBus == @"YES") && ([self containsString:@"bus" inOriginalNSSString:serviceKey]) ||
	   ((statePreloadedBizi == @"YES") && ([self containsString:@"bizi" inOriginalNSSString:serviceKey])) ||
	   ((statePreloadedWifi == @"YES") && ([self containsString:@"wifi" inOriginalNSSString:serviceKey])))
	{
	 */
		if (([lastUpdate doubleValue] + secondsInADay) > [now timeIntervalSince1970]) {
			NSString *dataKey = [[NSString alloc] initWithFormat:@"%@-data", serviceKey];
			data = [defaults objectForKey:dataKey];
			[dataKey release];
			NSLog(@"Loaded data from user defaults");
		}
	

		//DNDzgzAppDelegate *delegateVariable = (DNDzgzAppDelegate *)[UIApplication sharedApplication].delegate;
		//NSLog(@"preloaded antes de asignar: %@", delegateVariable.preLodaded);
		//delegateVariable.preLodaded = @"NO";
		//NSLog(@"preloaded despues de asignar: %@", delegateVariable.preLodaded);
	//}
	
	if (!data)
	{
		[self setSearchingStatus:YES];
		responseData = [[NSMutableData data] retain];
		NSString* url = [NSString stringWithFormat:@"http://2.latest.dnd-zgz.appspot.com/fetch?service=%@", serviceKey];
		NSLog(@"%@", url);
		NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
		[[NSURLConnection alloc] initWithRequest:request delegate:self];
		NSLog(@"Loading data from url");
	}
	else 
	{
		[self loadData:data];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error de conexión"
														message:@"Compruebe que está conectado a Internet e inténtelo de nuevo."
														delegate:self
											   cancelButtonTitle:@"Aceptar"
											   otherButtonTitles:nil];	
	[alertView show];
	[alertView release];
	[connection release];
	[responseData release];
	[self setSearchingStatus:NO];
}

- (void) observeValueForKeyPath: (NSString *) keyPath
                       ofObject: (id) object
                         change: (NSDictionary *) change
                        context: (void *) context
{
	if (localized == NO && keyPath == @"location")
	{
		for (id item in change)
		{
			id value = [change objectForKey:item];
			if ([value isKindOfClass: [CLLocation class]]) 
			{
				[self moveToUserLocation];
				centerButton.enabled = YES;
				localized = YES;
			}
		}	
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	[connection release];
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[self loadData: responseString];
	[responseData release];
	[responseString release];
	[self setSearchingStatus:NO];
}

- (void)loadData:(NSString *)responseString
{
	NSArray *places = [[NSArray alloc] initWithArray:[responseString JSONValue]];
	
	for (NSDictionary *dict in places) 
	{
		NSNumber *lat = [dict objectForKey:@"lat"];
		NSNumber *lon = [dict objectForKey:@"lon"];
		CLLocationCoordinate2D coordinate = { [lat doubleValue], [lon doubleValue] };
		
		MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinate:coordinate];
		annotation.title = [dict objectForKey:@"title"];
		annotation.subtitle = [dict objectForKey:@"subtitle"];
		annotation.identifier = [dict objectForKey:@"id"];
		annotation.service = serviceKey;
		[mapView addAnnotation:annotation];
		[annotation release];
		mapView.delegate = self;
	}
	
	[places release];
	
	// save data in database
	NSDate *now = [NSDate date];
	NSNumber *value = [NSNumber numberWithDouble:[now timeIntervalSince1970]];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setValue:value forKey:[NSString stringWithFormat:@"%@-lastUpdate", serviceKey]];
	[defaults setValue:responseString forKey:[NSString stringWithFormat:@"%@-data", serviceKey]];
	[defaults synchronize];
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)moveToUserLocation
{
	CLLocationCoordinate2D userNow = [[[mapView userLocation] location] coordinate];
	//CLLocationCoordinate2D pos = [(DNDzgzAppDelegate *)[UIApplication sharedApplication] myPosition];
	//pos = userNow;
	[mapView setCenterCoordinate:userNow animated:YES];
}

#pragma mark -
#pragma mark MapView delegate methods

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
	if ([annotation isKindOfClass:[MKUserLocation class]])
	{
		return nil; // No pin if this is the user location. We want the dot and concnetric circle, and continual updates
	}
	
	MyAnnotation* myan = (MyAnnotation*) annotation;
	
	if ([myan.identifier length] > 0)
	{
		MKPinAnnotationView *pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pinCustom"] autorelease];
		pinView.pinColor = MKPinAnnotationColorRed;
		pinView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
		pinView.canShowCallout = YES;
		pinView.calloutOffset = CGPointMake(-5, 5);

		return pinView;
	}
	else 
	{
		return nil;
	}
}
 
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
	MyAnnotation* annotation = (MyAnnotation*) [view annotation];
	
	DetailsView *infoView = [[DetailsView alloc] initWithNibName:@"DetailsView" bundle:nil];
	NSLog(@"Creating infoView");
	[infoView setAnnotation:annotation];
	NSLog(@"InfoView created");
	[self.navigationController pushViewController:infoView animated:YES];
	[infoView release];
	
	[self.mapView deselectAnnotation:annotation animated:NO];
	[self.mapView selectAnnotation:annotation animated:NO];
}

/*
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views;
{
    [self.mapView selectAnnotation:[[self.mapView annotations] lastObject] animated:YES];
}
*/

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden 
{
    // Remove HUD from screen when the HUD was hidded
    [hud removeFromSuperview];
    [hud release];
}

- (void)setSearchingStatus:(BOOL)isSearching
{
	//when network action, toggle network indicator and activity indicator
	if (isSearching) 
	{
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		
		UIWindow *window = [UIApplication sharedApplication].keyWindow;
		hud = [[MBProgressHUD alloc] initWithWindow:window];
		[window addSubview:hud];
		hud.labelText = @"Cargando...";
		[hud show:YES];
	} 
	else 
	{
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		
		[hud hide:YES];
		[hud removeFromSuperview];
		[hud release];
	}	
}

#pragma mark -
#pragma mark Swipe mapView

- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
    NSLog(@"map loaded");
}

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated 
{
    NSLog(@"map moving");
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    NSLog(@"map moved");
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning
{
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc 
{
	mapView.showsUserLocation = NO;
	mapView.delegate = nil;
	[mapView removeAnnotations:mapView.annotations];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:@"location" object:nil];
	[serviceKey release];
	if (centerButton != nil) {
		[centerButton release];
	}
	
	[super dealloc];
}

@end